<script lang="ts" setup>
import { Loader2, LogIn } from 'lucide-vue-next';
import { toTypedSchema } from '@vee-validate/zod';
import * as z from 'zod';
import type { GenericObject } from 'vee-validate';
import type { FetchResponse } from 'ofetch';
import { useToast } from '~/components/ui/toast';
import { useUserStore } from '~/composables/store/user-store';
import { userApi, type UserLogin } from '~/utils/api/user-api';
import type { Result } from '~/utils/api/type';

definePageMeta({
	layout: 'none',
}); // 隐藏导航栏

const router = useRouter();
const { toast } = useToast();
const userStore = useUserStore();
const isLoading = ref(false);

// -------- 表单校验 --------
const formSchema = toTypedSchema(z.object({
	email: z.string({ required_error: '邮箱不能为空' }).email({ message: '请输入有效的邮箱地址' }),
	password: z.string({ required_error: '密码不能为空' }).min(6, { message: '密码至少6位' }),
}));

function onSubmit(obj: GenericObject) {
	const values = obj as UserLogin;

	isLoading.value = true;
	userApi.userLogin(values).then(async (res) => {
		if (res.code === 200) {
			// 设置token
			userStore.setUser({
				refreshToken: res.data.refreshToken,
				accessToken: res.data.accessToken,
			});
			// 获取用户信息
			const userInfoResult = await userApi.getUserInfo();
			// 设置用户信息
			userStore.setUser({
				userInfo: userInfoResult.data,
			});
			toast({ description: '登录成功' });
			await router.push('/');
		}
	}).catch((err: FetchResponse<Result<UserLogin>>) => {
		toast({
			description: typeof err._data?.message == 'string' ? err._data.message : err._data?.message[0],
		});
	}).finally(() => {
		isLoading.value = false;
	});
}

let hasBackBeenCalled = false;

function back() {
	if (!hasBackBeenCalled) {
		router.back();
		hasBackBeenCalled = true;
	}
}
</script>

<template>
	<div>
		<FloatBack @click="back" />
		<!-- 忘记密码 -->
		<div
			class="w-full h-[100vh] lg:grid lg:grid-cols-2"
		>
			<div class="h-full flex items-center justify-center py-12">
				<div class="mx-auto grid w-[350px] gap-6">
					<div class="grid gap-5 text-center">
						<h1 class="text-3xl font-bold">
							登录
						</h1>
						<p class="text-balance text-muted-foreground">
							在下面输入您的电子邮件以登录您的帐户
						</p>
					</div>
					<div>
						<Form
							:validation-schema="formSchema"
							class="grid gap-5"
							@submit="onSubmit"
						>
							<!-- 邮箱 -->
							<FormField
								v-slot="{ componentField }"
								name="email"
							>
								<FormItem>
									<FormLabel>邮箱</FormLabel>
									<FormControl>
										<Input
											placeholder="my@example.com"
											type="email"
											v-bind="componentField"
										/>
									</FormControl>
									<FormMessage />
								</FormItem>
							</FormField>
							<!-- 密码 -->
							<FormField
								v-slot="{ componentField }"
								name="password"
							>
								<FormItem>
									<FormLabel>
										<div class="flex justify-between items-center">
											密码
											<a
												class="text-sm font-medium text-slate-600"
												href="/forgot-password"
											>忘记密码？ </a>
										</div>
									</FormLabel>
									<FormControl>
										<Input
											type="password"
											v-bind="componentField"
										/>
									</FormControl>
									<FormMessage />
								</FormItem>
							</FormField>
							<Button
								:disabled="isLoading"
								class="w-full"
								type="submit"
							>
								<template v-if="isLoading">
									<Loader2 class="mr-2 h-4 w-4 animate-spin" />
									稍等片刻
								</template>
								<template v-else>
									<LogIn class="w-4 h-4 mr-2" />
									立即登录
								</template>
							</Button>
						</Form>
					</div>
					<div class=" text-center text-sm">
						没有账户？
						<a
							class="underline"
							href="/register"
						>
							立即注册
						</a>
					</div>
				</div>
			</div>
			<div class="hidden bg-muted lg:block lg:h-full">
				<img
					alt="Image"
					class="h-[100vh] w-full object-cover dark:brightness-[0.2] dark:grayscale"
					src="@/assets/image/cover.jpg"
				>
			</div>
		</div>
	</div>
</template>

<style lang="postcss" scoped>

</style>
